package GUI;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.Vector;

import javax.swing.JLabel;
import javax.swing.JPanel;

public class GraphHandler extends JPanel 
{
	private int height = 480;
	private int width = 640;
	private int marginX = 100;
	private int marginY = 50;
	private int marginVerticalY = 15;
	private int labelMarginY = 20;
	private int labelMarginX = 30;
	private int ovalSize = 6; 
	
	private Vector<GraphDescriber> splines; 
	
	public GraphHandler() 
	{
		splines = new Vector<GraphDescriber>();
		
		this.setSize(width,height);
		this.setLocation(0, 0);
		this.setBackground(Color.WHITE);
		this.setLayout(null);
		this.setVisible(true);
	}
	
	/**
	 * draws each of the graphs described at splines.
	 */
	protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.drawAxis(g);
        for(GraphDescriber GD: splines)
        	this.drawVector(g, GD);
    }
	/**
	 * draws the axis of the graph
	 * @param g - graphics
	 */
	private void drawAxis(Graphics g)
	{
		/// Y axis
		g.drawLine(marginX, marginVerticalY, marginX, height+marginVerticalY);
		/// X axis
		g.drawLine(marginX, height+marginVerticalY,marginX+width, height+marginVerticalY);
		
		/// X axis's grid
		for (int i = 0; i < 8; i++) 
		{
			int x = marginX + i*(width/8);
			g.drawLine(x, height+marginVerticalY + 3 ,x, height+marginVerticalY - 3);
			
			JLabel l = new JLabel( "" + (i*10)); 
			l.setBounds(x, height+labelMarginY, 10, 10);
			l.setVisible(true);
			add(l);
		}
		
		/// Y axis's grid
		for (int i = 0; i < 5; i++) 
		{
			int y = height+marginVerticalY - i*(height/5);
			g.drawLine(marginX-3, y ,marginX+3, y);
			
			JLabel l = new JLabel( "" + (i*0.2)); 
			l.setBounds(marginX-labelMarginX, y-5, 50, 10);
			l.setVisible(true);
			add(l);
		}
	}
	
	/**
	 * draw the spline on the panel
	 * @param g - graphics
	 * @param avarageCd - spline
	 */
	public void drawVector(Graphics g, GraphDescriber avarageCd )
	{
		
		for (int i = 0; i < avarageCd.getSpline().size(); i++) 
		{
			int x = marginX + (i+1)*(width/80) - (int)ovalSize/2; 
			int y = (int)(height+marginVerticalY - (height)*(avarageCd.getSpline().elementAt(i)/1)) - ovalSize/2;
			g.setColor(avarageCd.getSplineColor());
			g.fillOval(x, y, ovalSize, ovalSize);
		}
	}
	
	/**
	 * adding a spline to show on the panel
	 * @param GD - graph describer
	 */
	public void addSpline(GraphDescriber GD)
	{
		if(GD != null)
		{
			splines.add(GD);
		}
		else
			System.out.println("Error: in setAvarageCd, GraphDescriber is null.");
		repaint();
	}
}
